package com.tpsix.security.image;

import com.tpsix.security.Constant;
import com.tpsix.security.ValidateCodeException;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Image captcha filter
 *
 * @author springer
 */
@Component
@AllArgsConstructor
public class CaptchaFilter extends OncePerRequestFilter {

    /**
     * Captcha key parameter name
     */
    private static final String CAPTCHA_KEY = "key";

    /**
     * captcha parameter name
     */
    private static final String CAPTCHA = "captcha";

    /**
     * Request method
     */
    private static final String POST = "POST";

    /**
     * Request uri
     */
    private static final String CAPTCHA_LOGIN_PATH = "/login";

    /**
     * Redis template
     */
    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * Authentication failure processor
     */
    private final AuthenticationFailureHandler authenticationFailureHandler;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String key = request.getParameter(CAPTCHA_KEY);
        if (CAPTCHA_LOGIN_PATH.equals(request.getRequestURI()) && !StringUtils.isEmpty(key) && POST.equalsIgnoreCase(request.getMethod())) {
            try {
                validateCode(request);
            } catch (ValidateCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * Validate image captcha
     * @param request
     */
    private void validateCode(HttpServletRequest request) {
        String key = obtainKey(request);
        String captcha = obtainCaptcha(request);
        if (StringUtils.isEmpty(captcha)) {
            throw new ValidateCodeException("captcha ");
        }
        Object captchaVal = redisTemplate.opsForValue().get(Constant.TPSIX_CAPTCHA_KEY + key);
        if (Objects.isNull(captchaVal)) {
            throw new ValidateCodeException("验证码已失效");
        }
        if (!captcha.toLowerCase().equals(captchaVal)) {
            throw new ValidateCodeException("验证码错误");
        }
    }

    private String obtainKey(HttpServletRequest request) {
        return request.getParameter(CAPTCHA_KEY);
    }

    private String obtainCaptcha(HttpServletRequest request) {
        return request.getParameter(CAPTCHA);
    }

}
